package iterator;

import java.util.ArrayList;
import java.util.Iterator;

public class BookShelf {
    private ArrayList<Book> books;
    private int last = 0;

    public BookShelf(int maxSize) {
        this.books = new ArrayList<>(maxSize);
    }

    public Book getBookAt(int i) {
        return books.get(i);
    }

    public void appendBook(Book book) {
        books.add(book);
        last++;
    }

    public int getLength() {
        return last;
    }

    public Iterator<Book> iterator() {
        return new BIterator(this);
    }

    private static class BIterator implements Iterator<Book> {
        private final BookShelf bookShelf;
        private int index;

        public BIterator(BookShelf bookShelf) {
            this.bookShelf = bookShelf;
            index = 0;
        }

        @Override
        public boolean hasNext() {
            return index < bookShelf.getLength();
        }

        @Override
        public Book next() {
            Book book = bookShelf.getBookAt(index);
            index++;
            return book;
        }
    }

    public static void main(String[] args) {

        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("Around the World in 80 Days"));
        bookShelf.appendBook(new Book("Bible"));
        bookShelf.appendBook(new Book("Cinderella"));
        bookShelf.appendBook(new Book("Daddy-Long-Legs"));
        Iterator<Book> it = bookShelf.iterator();
        while (it.hasNext()) {
            Book book = it.next();
            System.out.println(book.getName());

        }
    }
}
